package ltd.jdsoft.cute.channel.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ltd.jdsoft.cute.cache.CacheClient;
import ltd.jdsoft.cute.cache.CacheKeyUtil;
import ltd.jdsoft.cute.cache.callback.GetCallback;
import ltd.jdsoft.cute.channel.dao.OrgChannelConfigDAO;
import ltd.jdsoft.cute.channel.model.OrgChannelConfig;
import ltd.jdsoft.cute.channel.selector.ChannelSelector;

@Service
public class OrgChannelConfigService {

  @Autowired
  private OrgChannelConfigDAO orgChannelConfigDAO;
  public static final CacheKeyUtil keyUtil = new CacheKeyUtil(OrgChannelConfig.class);

  public void add(OrgChannelConfig orgChannelConfig) {
    orgChannelConfigDAO.add(orgChannelConfig);
    CacheClient.remove(keyUtil.getGroupKey(
        ".orgId." + orgChannelConfig.getOrgId() + ".type." + orgChannelConfig.getType()));
    // 删除缓存的可用通道
    CacheClient.remove(ChannelSelector.keyUtil
        .getRecKey(".channels." + orgChannelConfig.getOrgId() + "." + orgChannelConfig.getType()));
  }

  public void delete(long id) {
    OrgChannelConfig orgChannelConfig = orgChannelConfigDAO.get(id);
    orgChannelConfigDAO.delete(id);
    CacheClient.remove(keyUtil.getGroupKey(
        ".orgId." + orgChannelConfig.getOrgId() + ".type." + orgChannelConfig.getType()));
    // 删除缓存的可用通道
    CacheClient.remove(ChannelSelector.keyUtil
        .getRecKey(".channels." + orgChannelConfig.getOrgId() + "." + orgChannelConfig.getType()));
  }

  public void update(OrgChannelConfig orgChannelConfig) {
    orgChannelConfigDAO.update(orgChannelConfig);
    CacheClient.remove(keyUtil.getGroupKey(
        ".orgId." + orgChannelConfig.getOrgId() + ".type." + orgChannelConfig.getType()));
    // 删除缓存的可用通道
    CacheClient.remove(ChannelSelector.keyUtil
        .getRecKey(".channels." + orgChannelConfig.getOrgId() + "." + orgChannelConfig.getType()));
  }

  public List<OrgChannelConfig> get(long orgId, int type) {
    return CacheClient.get(keyUtil.getRecKey(".orgId." + orgId + ".type." + type),
        new GetCallback<List<OrgChannelConfig>>() {

          @Override
          public String getCacheGroup() {
            return keyUtil.getGroupKey(".orgId." + orgId + ".type." + type);
          }

          @Override
          public List<OrgChannelConfig> getObject() {
            return orgChannelConfigDAO.getChannelList(orgId, type);
          }
        });
  }
}
